#include "KMNetMsgOut.h"
#include <cstdlib>
#include "enet/enet.h"

const unsigned int kInitialDataSize = 16;
const unsigned int kSizeDataMultiplier = 2;

KMNetMsgOut::KMNetMsgOut():
    mDataSize(kInitialDataSize)
{
    mData = (char*) malloc(kInitialDataSize);
}

KMNetMsgOut::~KMNetMsgOut()
{
    free(mData);
}

char *KMNetMsgOut::getData() const
{
    return mData;
}

unsigned int KMNetMsgOut::getLength() const
{
    return mPos;
}

void KMNetMsgOut::expand(unsigned int bytesToAdd)
{
    unsigned int bytes = mPos+bytesToAdd;

    if (bytes > mDataSize)
    {
        do
        {
            mDataSize *= kSizeDataMultiplier;
        }
        while (bytes > mDataSize);

        mData = (char*) realloc(mData, mDataSize);
    }
}

void KMNetMsgOut::writeId(const int &id)
{
    write2Bytes(id);
}
void KMNetMsgOut::writeString(const std::string &str)
{
    int length = str.length();
    write2Bytes(length);

    expand(length);
    memcpy(mData + mPos, str.c_str(), length);
    mPos += length;
}

void KMNetMsgOut::write2Bytes(const int &val)
{
    expand(2);
    uint16_t t = ENET_HOST_TO_NET_16(val);
    memcpy(mData + mPos, &t, 2);
    mPos += 2;
}
